package jwt

import (
	"gindemo/pkg/jwt"
	"net/http"

	"github.com/gin-gonic/gin"
)

func JWTAuth(r *gin.Context) {
	reqUrl := r.FullPath()
	if reqUrl == "/api/auth/login" || reqUrl == "/api/auth/logout" {
		r.Next()
		return
	}
	// 查询请求头是否带token
	tokenStr := r.Request.Header.Get("Authorization")
	if tokenStr == "" {
		r.JSON(http.StatusOK, gin.H{
			"status":  http.StatusUnauthorized,
			"message": "用户未登录，请登录",
		})
		// 终止请求
		r.Abort()
		return
	}
	claims, err := jwt.ParseJwt(tokenStr)
	if err != nil {
		r.JSON(http.StatusOK, gin.H{
			"status":  http.StatusUnauthorized,
			"message": "token解析失败",
		})
		r.Abort()
		return
	}
	r.Set("claims", claims)
	r.Next()
}
